package com.feng.controller;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {
    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg", "hello,shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add(){
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update(){
        return "user/update";
    }

    @RequestMapping("/tologin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
/*    public String login(@PathVariable("username")String username,
                        @PathVariable("password") String password,
                        Model model){*/
        /**
         * 使用@PathVariable注解报错：Required URI template variable 'username' for method parameter type String is not present]
         */
    public String login(@RequestParam("username")String username,
                        @RequestParam("password") String password,
                        Model model){
//    public String login(String username,
//                        String password,
//                        Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录信息
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
          /*  Session session = subject.getSession();
            session.setAttribute("loginUser",username);*/
            return "index";
        } catch (UnknownAccountException e) {
            //e.printStackTrace();
            model.addAttribute("token_msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            //e.printStackTrace();
            model.addAttribute("token_msg","密码错误");
            return "login";
        }/*finally {
            Session session = subject.getSession();
            session.setAttribute("loginUser",username);
            return "index";
        }*/
    }


    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问此页面";
    }
}
